﻿using System;
using SysSU.Net;
using System.Threading;
using System.Collections.Generic;
using SysSU.UbiBroker.Interfaces;

namespace SysSU.UbiBroker
{
    public class UbiBroker : INetworkObserver
    {
        private readonly TCPNetworkClient tcpClient;
        private readonly TCPNetwokServer tcpServer;
        private readonly IList<IReaction> reactions;
        private readonly int reactionsPort;

        private UbiBroker(String ubicentreAddress, int ubiCentrePort, int reactionsPort) 
        {
            tcpClient = new TCPNetworkClient(ubicentreAddress, ubiCentrePort);
            tcpServer = new TCPNetwokServer(reactionsPort);
            reactions = new List<IReaction>();
            this.reactionsPort = reactionsPort;
        }

        public static UbiBroker createInstance(string ubicentreAddress, int ubicentrePort, int reactionsPort) 
    	{
            var instance = new UbiBroker(ubicentreAddress, ubicentrePort, reactionsPort);
            new Thread(instance.Run).Start();
            return instance;
        }

        internal String SendMessage(String message)
        {
            return tcpClient.SendMessage(message);
        }

        internal void AddReaction(IReaction reaction) 
        {
            reactions.Add(reaction);
        }

        public IDomain GetDomain(String name) 
        {
            return new Domain(name, this);
        }

        public String Process(NetworkMessageReceived message) 
        {        
            return null;
        }

        private void Run() 
        {
            tcpServer.Observer = this;
            tcpServer.Start();
        }
    }
}
